<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:common:add']">新增</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="commonList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="用户ID" align="center" prop="commonId" /> -->
      <el-table-column label="分账类别" align="left" prop="accountType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.account_type" :value="scope.row.accountType" />
        </template>
      </el-table-column>
      <!-- 01 角色 roleMerchant  merchantRatio-->
      <el-table-column label="角色" align="left" prop="roleMerchant">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.radit_role" :value="scope.row.roleMerchant" />
        </template>
      </el-table-column>
      <el-table-column label="分账比例" align="left" prop="merchantRatio" />
      <!-- 02 roleProvince  provinceRatio-->
      <el-table-column label="代理角色" align="left" prop="roleProvince">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.radit_role" :value="scope.row.roleProvince" />
        </template>
      </el-table-column>
      <el-table-column label="分账比例" align="left" prop="provinceRatio" />
      <!-- 03 roleCity  cityRatio-->
      <el-table-column label="代理角色" align="left" prop="roleCity">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.radit_role" :value="scope.row.roleCity" />
        </template>
      </el-table-column>
      <el-table-column label="分账比例" align="left" prop="cityRatio" />

      <!-- 04 role_procedure procedure_ratio-->
      <el-table-column label="角色" align="left" prop="roleProcedure">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.radit_role" :value="scope.row.roleProcedure" />
        </template>
      </el-table-column>
      <el-table-column label="分账比例" align="left" prop="procedureRatio" />
      <!-- 05 roleService  serviceRatio-->
      <el-table-column label="角色" align="left" prop="roleService">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.radit_role" :value="scope.row.roleService" />
        </template>
      </el-table-column>
      <el-table-column label="分账比例" align="left" prop="serviceRatio" />
      <el-table-column label="状态" align="left" prop="commonStatus">
        <template slot-scope="scope">
          <div v-if="scope.row.commonStatus==='0'"><el-tag type="info">生效</el-tag></div>
          <div v-else-if="scope.row.commonStatus==='1'"><el-tag type="success">未生效</el-tag></div>
          <div v-else></div>
        </template>
      </el-table-column>
      <el-table-column label="生效时间" align="left" prop="beginTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.beginTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="作废时间" align="left" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作人" align="left" prop="editUser" />
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改商代参数对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="分账类别" prop="accountType">
              <el-input disabled v-model="form.accountType" placeholder="请输入分账类别" />
            </el-form-item>
          </el-col>
          <el-col :span="12"></el-col>
        </el-row>
        <!-- 商家 roleMerchant   merchantRatio-->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商家" prop="roleMerchant">
              <el-input disabled v-model="form.roleMerchant" placeholder="商家" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分成比例" prop="merchantRatio">
              <el-input v-model="form.merchantRatio" placeholder="请输入分成比例"> 
                <template slot="prepend">订单金额的</template>
                <template slot="append">%</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 省代理 roleProvince provinceRatio-->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="代理角色" prop="roleProvince">
              <el-input disabled v-model="form.roleProvince" placeholder="省代理">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分成比例" prop="provinceRatio">
              <el-input v-model="form.provinceRatio" placeholder="请输入分成比例">
                <template slot="prepend">订单金额的</template>
                <template slot="append">%</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 市县代理 roleCity cityRatio-->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="代理角色" prop="roleCity">
              <el-input disabled v-model="form.roleCity" placeholder="市/县代理" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分成比例" prop="cityRatio">
              <el-input v-model="form.cityRatio" placeholder="请输入分成比例"> 
                <template slot="prepend">订单金额的</template>
                <template slot="append">%</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 平台 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="角色" prop="roleProcedure">
              <el-input disabled v-model="form.roleProcedure" placeholder="平台" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分成比例" prop="procedureRatio">
              <el-input v-model="form.procedureRatio" placeholder="请输入分成比例"> 
                <template slot="prepend">订单金额的</template>
                <template slot="append">%</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 财务银行手续费 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="角色" prop="roleService">
              <el-input disabled v-model="form.roleService" placeholder="财务银行手续费" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分成比例" prop="serviceRatio">
              <el-input v-model="form.serviceRatio" placeholder="请输入分成比例">
                <template slot="prepend">订单金额的</template>
                <template slot="append">%</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-popconfirm title="是否确定要实施该分账比例？" @confirm="submitForm">
          <el-button slot="reference" type="primary">确 定</el-button>
        </el-popconfirm>
        <el-button style="margin-left: 10px;" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listCommon,
    getCommon,
    delCommon,
    addCommon,
    updateCommon,
    walletCommon,
  } from "@/api/system/common";

  export default {
    name: "Common",
    dicts: ['account_type', 'radit_role'],
    data() {
      var validateNumber = (rule, value, callback) => {
        console.log(value,'value')
        var pattern = /^(0|([1-9][0-9]*))(\.[\d]{0,1})?$/
        if (!pattern.test(value)) {
          callback(new Error('请输入一个数字，并确保小数点后仅有一位'));
        } else if(value>=100){
          callback(new Error('总分账比例不能超过100%，请重新输入合规值'));
        }else if(value==='0'){
          callback(new Error('请输入分成比例'));
        } else {
          callback()
        }
      };

      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 商代参数表格数据
        commonList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          accountType: null,
          roleProvince: null,
          provinceRatio: null,
          roleCity: null,
          cityRatio: null,
          roleCount: null,
          countRatio: null,
          roleService: null,
          serviceRatio: null,
          commonStatus: null,
          beginTime: null,
          endTime: null,
          editUser: null,
          crTime: null,
          upTime: null,
          commonField1: null,
          commonField2: null,
          commonField3: null,
          commonField4: null,
          commonField5: null
        },
        // 表单参数
        form: {
          roleMerchant: '商家',
          merchantRatio: '97.4',
          roleProvince: '省代理',
          provinceRatio: '0.3',
          roleCity: "市/县代理",
          cityRatio: '0.7',
          roleProcedure: '平台',
          procedureRatio: '1',
          roleService: '财务银行手续费',
          serviceRatio: '0.6',
          accountType: '推广销售分佣'
        },
        // 表单校验
        rules: {
          merchantRatio: [{
            required: true,
            message: '请输入分成比例',
            trigger: 'change'
          },{ validator: validateNumber, trigger: 'change' }],
          provinceRatio: [{
            required: true,
            message: '请输入分成比例',
            trigger: 'change'
          },{ validator: validateNumber, trigger: 'change' }],
          cityRatio: [{
            required: true,
            message: '请输入分成比例',
            trigger: 'change'
          },{ validator: validateNumber, trigger: 'change' }],
          procedureRatio: [{
            required: true,
            message: '请输入分成比例',
            trigger: 'change'
          },{ validator: validateNumber, trigger: 'change' }],
          serviceRatio: [{
            required: true,
            message: '请输入分成比例',
            trigger: 'change'
          },{ validator: validateNumber, trigger: 'change' }]
        },
        // 状态(0 未生效 1-生效)
        commonStatusList: [{
            dictLabel: "未生效",
            dictSort: 0
          },
          {
            dictLabel: "生效",
            dictSort: 1
          }
        ]
      };
    },
    created() {
      this.getList();
    },
    methods: {
      /** 查询商代参数列表 */
      getList() {
        this.loading = true;
        listCommon(this.queryParams).then(response => {
          this.commonList = response.data;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        // this.form = {
        //   roleProvince: null,
        //   provinceRatio: null,
        //   roleCity: null,
        //   cityRatio: null,
        //   roleProcedure: null,
        //   procedureRatio: null,
        //   roleService: null,
        //   serviceRatio: null,
        //   accountType:null
        // };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.commonId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "新增分账类别";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const commonId = row.commonId || this.ids
        getCommon(commonId).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "新增分账类别";
        });
      },

      getCurrentDateTime() {
        const now = new Date();
        const year = now.getFullYear();
        const month = (now.getMonth() + 1).toString().padStart(2, '0');
        const day = now.getDate().toString().padStart(2, '0');
        const hours = now.getHours().toString().padStart(2, '0');
        const minutes = now.getMinutes().toString().padStart(2, '0');
        const seconds = now.getSeconds().toString().padStart(2, '0');

        // return `${year}-${month}-${day} ${hours}:${minutes}`;
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      },

      /** 提交按钮 */
      submitForm() {
        const Decimal = require('decimal.js')
        const num1 = Decimal(this.form.merchantRatio);
        const num2 = Decimal(this.form.provinceRatio);
        const num3 = Decimal(this.form.cityRatio);
        const num4 = Decimal(this.form.procedureRatio);
        const num5 = Decimal(this.form.serviceRatio);
        const remainder = num1.add(num2).add(num3).add(num4).add(num5);
        console.log(Number(remainder),'remainderremainder')

        if(Number(remainder)>100){
          this.$modal.msgError("总分账比例不能超过100%，请重新输入合规值");
          return
        }

        if(Number(remainder)<100){
          this.$modal.msgError("总分账比例只能等于100，请重新输入合规值");
          return
        }

        const num6 = Decimal(100);
        console.log('0004')
        this.$refs["form"].validate(valid => {
          if (valid) {
            let params = {
              "accountType": "1",
              // 商家
              "roleMerchant": "1", //商家
              "merchantRatio": Decimal(this.form.merchantRatio).div(num6), //商家分成比例
              // 省
              "roleProvince": "2", //省代理
              "provinceRatio": Decimal(this.form.provinceRatio).div(num6), //省代理-分账比例
              // 市
              "roleCity": "3", //市/县代理
              "cityRatio": Decimal(this.form.cityRatio).div(num6), //市/县-分账比例--取市
              // 平台
              "roleProcedure": "5", //平台
              "procedureRatio": Decimal(this.form.procedureRatio).div(num6), //平台分成比例
              // 财务银行手续费
              "roleService": "6", //财务银行手续费
              "serviceRatio": Decimal(this.form.serviceRatio).div(num6), //财务银行手续费-分账比例
            }
            updateCommon(params).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).catch(error=>{
            });
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const commonIds = row.commonId || this.ids;
        this.$modal.confirm('是否确认删除商代参数编号为"' + commonIds + '"的数据项？').then(function() {
          return delCommon(commonIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('system/common/export', {
          ...this.queryParams
        }, `common_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>
